//TreeMapTest1.java
package com.ylaihui.mapitf;

import java.util.*;

class Book{
    int id;
    String name;

    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Book book = (Book) o;
        return id == book.id &&
                Objects.equals(name, book.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name);
    }

    public Book(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public Book() {
    }
}
public class TreeMapTest1 {
    public static void main(String[] args) {
        TreeMap map = new TreeMap(new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                if(o1 instanceof Book && o2 instanceof Book){
                    Book b1 = (Book) o1;
                    Book b2 = (Book) o2;
                    return -Integer.compare(b1.id, b2.id);
                }
                else
                    throw new RuntimeException("不能比较的类型");
            }
        });

        Book b1 = new Book(111, "ylaihui");
        Book b2 = new Book(222, "ylaihui");
        Book b3 = new Book(555, "ylaihui");
        Book b4 = new Book(444, "ylaihui");

        map.put(b1,"ylaihui1");
        map.put(b2,"ylaihui2");
        map.put(b3,"ylaihui3");
        map.put(b4,"ylaihui4");

        Set set = map.entrySet();
        Iterator it = set.iterator();
        while (it.hasNext()){
            Object next = it.next();
            Map.Entry entry = (Map.Entry) next;
            System.out.println(entry.getKey() +":"+entry.getValue());
        }
    }
}
/*
Book{id=555, name='ylaihui'}:ylaihui3
Book{id=444, name='ylaihui'}:ylaihui4
Book{id=222, name='ylaihui'}:ylaihui2
Book{id=111, name='ylaihui'}:ylaihui1
 */
